import time
from mylib import Camera
import tf

# 初始化摄像头
camera = Camera()

# 模型和标签文件路径（SD卡根目录）
model_path = "/sd/model.tflite"
label_path = "/sd/label.txt"

# 加载模型和标签
print(f"Loading model: {model_path}\n")
tf_model = tf.load(model_path)

print(f"Loading labels: {label_path}\n")
with open(label_path, "r") as f:
    labels = [line.strip() for line in f]

def run_model(image):
    """
    在图像上运行模型并返回分类结果。
    """
    for obj in tf.classify(tf_model, image, min_scale=1.0, scale_mul=0.5, x_overlap=-1, y_overlap=-1):
        
        # 获取分类结果并排序
        sorted_list = sorted(zip(labels, obj.output()), key=lambda x: x[1], reverse=True)
        
        # 获取最可信的结果
        top_result = sorted_list[0]
        
        return top_result  # 返回 (标签, 置信度)
    
    return None  # 如果没有分类结果

# 主循环
while True:
    
    # 获取图像
    img_roi, fps = camera.get_image()
    
    # # 打印帧率
    # print(f"FPS: {fps}\n")
    
    # 运行模型
    result = run_model(img_roi)
    
    if result:
        print(f"Detected: {result[0]}  Confidence: {result[1]:.2f}\n")
    else:
        print("No detection\n")
    
    # 延迟，避免过度使用资源
    time.sleep(0.1)
